# tasks.py
import json
import time
from datetime import datetime

import pytz
from celery import shared_task, current_app

from Group.models import MemberTraining, MemberTrainingRecord
from Group.util import TrainStatus


@shared_task(name='check_member_training')
def check_member_training(member_training_id):
    try:
        print("Checking member training...", time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))

        training = MemberTraining.objects.get(id=member_training_id)
        now = datetime.now(pytz.timezone('Asia/Shanghai'))
        member = training.member

        # 检查当天是否有签到或请假记录，或者是已经生成了缺勤记录了
        existing_record = MemberTrainingRecord.objects.filter(
            training=training,
            create_time__date=now.date(),
            record_type__in=[TrainStatus.LEAVE, TrainStatus.ABSENCE, TrainStatus.REGISTERED]  # 已签到或请假
        )

        # 如果没有记录，生成缺勤记录
        if not existing_record.exists():
            MemberTrainingRecord.objects.create(
                member=member,
                training=training,
                record_type=TrainStatus.ABSENCE,  # 缺勤
                remark=f"未在规定时间签到，系统判定为缺勤！检查时间：{time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())}"
            )
        else:
            record = existing_record.first()
            if record.record_type == TrainStatus.REGISTERED:
                record.remark += f" boot:已签到，检查时间：{time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())}"
                record.save()
            elif record.record_type == TrainStatus.LEAVE:
                record.remark += f" boot:请假已检查，检查时间：{time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())}"
                record.save()
    except MemberTraining.DoesNotExist:
        pass


@shared_task
def cancel_task(task_id):
    current_app.control.revoke(task_id)


@shared_task(name='check_member_training_task')
def check_member_training_task():
    today = datetime.now().date()
    trainings = MemberTraining.objects.filter(
        training_type=0,
        start_time__date__lte=today,
        end_time__date__gte=today
    )

    if not trainings.exists():
        return
    weekday = datetime.now().weekday() + 1
    for training in trainings:
        days = json.loads(training.recurrence_days)
        if weekday in days:
            check_member_training.delay(training.id)
